//
//  MYPageControl.m
//  nobalmetal
//
//  Created by 汤丹峰 on 16/11/1.
//  Copyright © 2016年 judu. All rights reserved.
//

#import "MYPageControl.h"

@interface MYPageControl ()
{
    CGFloat labelM;
    CGFloat labelH;
    CGFloat labelW;
    CGFloat selLabelW;
    CGFloat labelX;
}
@property (nonatomic, strong) NSMutableArray *labelArr;

@end
@implementation MYPageControl
- (NSMutableArray *)labelArr
{
    if (!_labelArr)
    {
        _labelArr = [[NSMutableArray alloc] init];
    }
    return _labelArr;
}
- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor clearColor];
        labelM = 5;
        labelH = 3;
        labelW = 10;
        selLabelW = 14;
    }
    return self;
}

- (void)setNumberOfPages:(NSInteger)numberOfPages
{
    _numberOfPages = numberOfPages;
    if (numberOfPages <= 0) {
        return;
    }
    
    CGFloat sumLabelW = 0;
    if (numberOfPages == 1) {
        sumLabelW = selLabelW;
    } else {
        sumLabelW = selLabelW + (numberOfPages - 1) * (labelW + labelM);
    }
    labelX = self.width - sumLabelW;
    
    for (int i = 0; i < self.labelArr.count; i++) {
        UILabel *label = self.labelArr[i];
        [label removeFromSuperview];
    }
    [self.labelArr removeAllObjects];
    for (int i = 0; i < numberOfPages; i++) {
        UILabel *label = [[UILabel alloc] init];
        if (i == 0) {
            label.frame = CGRectMake(labelX, 0, selLabelW, labelH);
            label.alpha = 1.0;
        } else {
            label.frame = CGRectMake(labelX + selLabelW + labelM + (i - 1) * (labelW + labelM), 0, labelW, labelH);
            label.alpha = 0.5;
        }
        label.backgroundColor = [UIColor whiteColor];
        label.layer.cornerRadius = 1;
        label.layer.masksToBounds = YES;
        [self addSubview:label];
        [self.labelArr addObject:label];
    }
}
- (void)setCurrentPage:(NSInteger)currentPage
{
    _currentPage = currentPage;
    
    if (currentPage >= self.labelArr.count) {
        return;
    }
    for (int i = 0; i < self.labelArr.count; i++) {
        UILabel *label = self.labelArr[i];
        if (i == currentPage) {
            label.alpha = 1.0;
            label.width = selLabelW;
        } else {
            label.alpha = 0.5;
            label.width = labelW;
        }
        
        if (i <= currentPage) {
            label.x = labelX + i * (labelW + labelM);
        } else {
            label.x = labelX + selLabelW + labelM + (i - 1) * (labelW + labelM);
        }
    }
}
- (void)setHidesForSinglePage:(BOOL)hidesForSinglePage
{
    _hidesForSinglePage = hidesForSinglePage;
    
    if (self.numberOfPages == 1) {
        self.hidden = YES;
    } else {
        self.hidden = NO;
    }
}
@end
